//
//  ZYCodeContentView.m
//  ZYOils
//
//  Created by 段新瑞 on 2019/9/24.
//  Copyright © 2019 Mr.Xr. All rights reserved.
//

#import "ZYCodeContentView.h"
#import <ZXingObjC/ZXingObjC.h>

@interface ZYCodeContentView()

@property (weak, nonatomic) IBOutlet UIButton *setMoneyBtn;

@property (weak, nonatomic) IBOutlet UIButton *saveImageBtn;

@property (weak, nonatomic) IBOutlet UIImageView *codeImageView;


@property (weak, nonatomic) IBOutlet UIView *codeView;

@end

@implementation ZYCodeContentView

- (void)setJsonStr:(NSString *)jsonStr {
    _jsonStr = jsonStr;
    NSString *codeUrlString = jsonStr;
    ZXEncodeHints *hints = [ZXEncodeHints hints];
    hints.encoding = NSUTF8StringEncoding;// 设置编码类型
    // 设置纠正级别，越高识别越快
    hints.errorCorrectionLevel = [ZXQRCodeErrorCorrectionLevel errorCorrectionLevelH];
    hints.dataMatrixShape =ZXDataMatrixSymbolShapeHintForceSquare;
    hints.margin = [NSNumber numberWithInt:0.];
    
    ZXMultiFormatWriter *writer = [ZXMultiFormatWriter writer];
    ZXBitMatrix* result = [writer encode:codeUrlString format:kBarcodeFormatQRCode width:1000 height:1000 hints:hints error:nil];
    if (result) {
        CGImageRef image = [[ZXImage imageWithMatrix:result] cgimage];
        UIImage *image1 =   [UIImage imageWithCGImage:image];//二维码原图
        UIImage *subIamge = [UIImage imageNamed:@"AppIcon"];
        self.codeImageView.image = [self addSubImage:image1 sub:subIamge];//二维码里加图标，生成带logo的方法
    } else {
        self.codeImageView.image = nil;
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

/// 二维码中添加 logo
- (UIImage *)addSubImage:(UIImage *)img sub:(UIImage *) subImage {
    CGFloat ratio_width = 2;
    int w = img.size.width;
    int h = img.size.height;
    int subWidth = 100 * ratio_width;
    int subHeight = 100 * ratio_width;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //create a graphic context with CGBitmapContextCreate
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    CGContextDrawImage(context, CGRectMake( (w-subWidth)/2, (h - subHeight)/2, subWidth, subHeight), [subImage CGImage]);
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}
                   
                   
@end
